package com.tmp.alarm.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.LinkedList;

/**
 * MySQL工具类
 */
public class MySQLUtils {

	private final static Logger LOGGER = LoggerFactory.getLogger(MySQLUtils.class);
	
	protected static  PreparedStatement pstmt=null;

	protected  static  Statement statement = null;

	// 静态连接队列
	private static LinkedList<Connection> connectionQueue=null;

	private static  final String  JDBC_URL= PropertiesUtil.get("jdbc.url");
	private static  final String  JDBC_USERNAME= PropertiesUtil.get("jdbc.username");
	private static  final String  JDBC_PASSWORD= PropertiesUtil.get("jdbc.password");

	private static final int initConnections = Integer.parseInt(PropertiesUtil.get("jdbc.initConnections").trim());//初始化连接池大小
	private static final int stepConnections = Integer.parseInt(PropertiesUtil.get("jdbc.stepConnections").trim());//每次增加的大小
	private static final int maxConnections = Integer.parseInt(PropertiesUtil.get("jdbc.maxConnections").trim());//连接池最大值
	private static  int curConnections =0;//当前连接池中实例大小
	private  static  int numbers = 0;

	public  static void  main(String[] args){

		LinkedList<String> lds = new LinkedList<String>();
		lds.push("aaa");
		lds.push("bbb");
		lds.push("cccc");
		LOGGER.info("lds  size =="+lds.size());

		String a = lds.poll();
		String b = lds.poll();
		String c = lds.poll();
		lds.push("ddd");
		String d = lds.poll();

		LOGGER.info("lds  size =="+lds.size()+"\n"+a+" "+b+" "+c+"|"+d +"...");

	}

	/**
	 * 获取特征库连接句柄
	 *
	 * @return
	 * @throws Exception
	 */
	public synchronized  static Connection getConnection() throws Exception {

		Connection connection = null;
		numbers++;
		try {
			if(connectionQueue !=null){
				if(connectionQueue.size()>0){
					//!!!暂时有个问题,如果maxConnection达到最大了,且现在全部被拿出去用了,没有返回到连接池中,现在也创建不了新的,所以就会取不到,这里先放一下
					LOGGER.info("connectionQueue不为null...,当前queue中数为:"+curConnections+"  访问请求获取链接次数为:"+numbers);
					connection = connectionQueue.poll();
					curConnections--;
				}else{
					LOGGER.info("connectionQueue里没有connection,当前queue中数为:"+curConnections+"  访问请求获取链接次数为:"+numbers);
					for (int i = 0; i < stepConnections; i++) {
						if (connectionQueue.size() <= maxConnections && curConnections <= maxConnections){
							Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
							connectionQueue.push(conn);
							curConnections++;
						}
					}
					connection = connectionQueue.poll();
					curConnections--;
				}
			}else{
				LOGGER.info("connectionQueue为null*** 链接首次创建,当前queue中数为:"+curConnections+"  访问请求获取链接次数为:"+numbers);
				connectionQueue = new LinkedList<Connection>();
				for(int i=0; i<initConnections; i++){
					Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
					connectionQueue.push(conn);
					curConnections++;
				}
				connection = connectionQueue.poll();
				curConnections--;
			}
		} catch (Exception e) {
			LOGGER.info("连接mysql异常..."+e.getMessage());
			throw new RuntimeException("连接mysql异常..."+e.getMessage());
		}
		return  connection;
		/*numbers = numbers+1;
		if(connection == null){
			synchronized (MySQLUtils.class){
				if(connection == null){
					LOGGER.info("connection为null*** 链接次数为:"+numbers);
					try {
						String tmp_url = "";
						String tmp_user = "";
						String tmp_pwd = "";
						Class.forName("com.mysql.jdbc.Driver").newInstance();
						connection= DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
						LOGGER.info("connection为null*** 链接次数为:"+numbers);
					} catch (Exception e) {
						LOGGER.error("重试创建连接句柄失败:"+e.getMessage());
					}
				}
			}
			return connection;
		}else{
			LOGGER.info("connection不为null...链接次数为:"+numbers);
			LOGGER.info("connection不为null...链接次数为:"+numbers);
			return connection;
		}*/
	}


	public synchronized static void returnConnection(Connection conn){
		if(conn !=null){
			LOGGER.info("归还connection,curConnetion为:"+curConnections);
			connectionQueue.push(conn);
			curConnections++;
		}else{
			LOGGER.info("归还connection,connection 为null...");
		}
	}


	public  static  void executeUpdate(Connection conn, String sql){

		try {
			statement = conn.createStatement();
			statement.execute(sql);
		} catch (SQLException e) {
			e.printStackTrace();
			LOGGER.info("异常的sql为:"+sql);
			throw  new RuntimeException("执行update异常..."+e.getMessage());
		}finally {
			try {
				close(statement);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 执行查询操作
	 *
	 * @param conn
	 * @param sql
	 * @return
	 * @throws Exception
	 */
	public static ResultSet query(Connection conn, String sql) throws Exception {

		ResultSet rs = null;
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
			throw  new RuntimeException("查询sql异常"+e.getMessage());
		}
		return  rs;
	}


	/**
	 * 关闭资源连接
	 *
	 * @param conn
	 * @throws Exception
	 */
	public static void close(Connection conn) throws Exception {
		try {
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			throw new RuntimeException("关闭connection异常"+e.getMessage());
		}
	}

	public static void  close(Statement statement) throws Exception{

		try {
			if(statement !=null){
				statement.close();
				statement = null;
			}
		}catch (SQLException e){
			throw new RuntimeException("关闭statment异常..."+e.getMessage());
		}
	}

	/**
	 * 关闭资源连接
	 *
	 * @param rs
	 * @throws Exception
	 */
	public static void close(ResultSet rs) throws Exception {
		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (pstmt != null) {
				pstmt.close();
				pstmt = null;
			}
		} catch (SQLException e) {
			throw new RuntimeException("关闭ResultSet异常"+e.getMessage());
		}
	}

}
